package controller

import (
	"a-common/myerr"
	"a-system/domain/entity"
	"a-system/service"
	"fmt"
	"sync"

	"github.com/gofiber/fiber/v2"
)

var (
	sysPostControllerTemp *SysPostController
	sysPostService        = service.NewSysPostService()
	sysPostControllerOnce sync.Once
)

type SysPostController struct{}

func NewSysPostController() *SysPostController {
	sysPostControllerOnce.Do(func() {
		sysPostControllerTemp = &SysPostController{}
	})
	return sysPostControllerTemp
}

// List 列表
func (m *SysPostController) List(c *fiber.Ctx) error {
	var args entity.SysPostDto
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	err := args.Validator()
	if err != nil {
		return err
	}

	// 查询
	pageVo, err := sysPostService.List(&args)
	if err != nil {
		return err
	}
	return Resp(c, pageVo)
}

// Del 删
func (m *SysPostController) Del(c *fiber.Ctx) error {
	ids := c.Params("ids")
	if ids == "" {
		return myerr.ERR_SYS_ARGS
	}
	_, err := sysPostService.Del(ids)
	if err != nil {
		return err
	}
	return Ok(c)
}

// Get 查
func (m *SysPostController) Get(c *fiber.Ctx) error {
	id := c.Params("id")
	if id == "" {
		return myerr.ERR_SYS_ARGS
	}
	data, err := sysPostService.Get(id)
	if err != nil {
		return err
	}
	return Resp(c, data)
}

// Add 增
func (m *SysPostController) Add(c *fiber.Ctx) error {
	var args entity.SysPostDto
	if err := c.BodyParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	user := GetUser(c)
	args.CreatedBy = user.Account

	_, err := sysPostService.Add(&args)
	if err != nil {
		return err
	}
	return Ok(c)
}

// Edit 改
func (m *SysPostController) Edit(c *fiber.Ctx) error {
	var args entity.SysPostDto
	if err := c.BodyParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	user := GetUser(c)
	args.UpdatedBy = user.Account

	_, err := sysPostService.Edit(&args)
	if err != nil {
		return err
	}
	return Ok(c)
}

// Export 导出
func (m *SysPostController) Export(c *fiber.Ctx) error {
	var args entity.SysPostDto
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}

	if args.PageNum < 1 {
		args.PageNum = 1
	}
	if args.PageSize < 1 {
		args.PageSize = 10
	}

	f, err := sysPostService.Export(&args)
	if err != nil {
		return err
	}

	c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, "岗位信息表"))
	err = f.Write(c.Response().BodyWriter())
	if err != nil {
		return err
	}
	return nil
}
